package com.heantai.easystruts.controller;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;

import com.heantai.easystruts.config.ActionBean;
import com.heantai.easystruts.config.ActionMappingsBean;
import com.heantai.easystruts.config.ForwardBean;


public class ActionServlet extends HttpServlet {
	private ActionMappingsBean amb;
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String uri =request.getRequestURI();
		String path=uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		ActionBean actionBean=amb.findActionBean(path);
		String type=actionBean.getType();
		try {
			Action action=(Action) Class.forName(type).newInstance();
			String rs=action.execute(request, response);
			ForwardBean forwardBean=actionBean.findForwardBean(rs);
			if(forwardBean.isRedirect()){
				response.sendRedirect(request.getContextPath()+forwardBean.getPath());//绝对路径
			}else{
				request.getRequestDispatcher(forwardBean.getPath()).forward(request, response);//绝对路径
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}
	@Override
	public void init() throws ServletException {
		Digester digester=DigesterLoader.createDigester(ActionServlet.class.getResource("/com/heantai/easystruts/config/rule.xml"));
//		Digester digester=DigesterLoader.createDigester(ActionServlet.class.getClassLoader().getResource("com/heantai/easystruts/config/rule.xml"));
		amb=new ActionMappingsBean();
		digester.push(amb);
		try {
			digester.parse(ActionServlet.class.getResourceAsStream("/easystructs-config.xml"));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		} 
	}
}
